/**
 * 性能监控工具
 */

/**
 * 测量函数执行时间
 */
export function measurePerformance<T>(
  fn: () => T,
  label: string = 'Function'
): T {
  const startTime = performance.now()
  const result = fn()
  const endTime = performance.now()
  
  console.log(`[Performance] ${label} took ${(endTime - startTime).toFixed(2)}ms`)
  
  return result
}

/**
 * 异步函数执行时间测量
 */
export async function measureAsyncPerformance<T>(
  fn: () => Promise<T>,
  label: string = 'Async Function'
): Promise<T> {
  const startTime = performance.now()
  const result = await fn()
  const endTime = performance.now()
  
  console.log(`[Performance] ${label} took ${(endTime - startTime).toFixed(2)}ms`)
  
  return result
}

/**
 * 节流函数
 */
export function throttle<T extends (...args: any[]) => any>(
  fn: T,
  delay: number = 300
): (...args: Parameters<T>) => void {
  let lastCall = 0
  
  return (...args: Parameters<T>) => {
    const now = Date.now()
    
    if (now - lastCall >= delay) {
      lastCall = now
      fn(...args)
    }
  }
}

/**
 * 内存使用监控
 */
export function logMemoryUsage(label: string = 'Memory'): void {
  if ('memory' in performance) {
    const memory = (performance as any).memory
    console.log(`[${label}] Memory usage:`, {
      usedJSHeapSize: `${(memory.usedJSHeapSize / 1048576).toFixed(2)} MB`,
      totalJSHeapSize: `${(memory.totalJSHeapSize / 1048576).toFixed(2)} MB`,
      jsHeapSizeLimit: `${(memory.jsHeapSizeLimit / 1048576).toFixed(2)} MB`
    })
  }
}

/**
 * 创建性能标记
 */
export class PerformanceTracker {
  private marks: Map<string, number> = new Map()
  
  start(name: string): void {
    this.marks.set(name, performance.now())
  }
  
  end(name: string): number | null {
    const startTime = this.marks.get(name)
    if (!startTime) {
      console.warn(`No start mark found for: ${name}`)
      return null
    }
    
    const duration = performance.now() - startTime
    console.log(`[Performance] ${name}: ${duration.toFixed(2)}ms`)
    this.marks.delete(name)
    
    return duration
  }
  
  clear(): void {
    this.marks.clear()
  }
}

// 全局性能追踪器实例
export const perfTracker = new PerformanceTracker()
